package com.backsidecode.service.impl;

import com.backsidecode.mapper.CourseVariableMapper;
import com.backsidecode.mapper.CoursesMapper;
import com.backsidecode.pojo.entity.CourseVariable;
import com.backsidecode.pojo.entity.Courses;
import com.backsidecode.pojo.entity.PageBean;
import com.backsidecode.service.CoursesService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class CoursesServiceImpl extends ServiceImpl<CoursesMapper, Courses>
        implements CoursesService {

    @Autowired
    CourseVariableMapper courseVariableMapper;

    @Override
    public PageBean getCoursePage(int page, int pageSize, String className) {
        //1.设置分页参数
        PageHelper.startPage(page, pageSize);//设置分页参数

        LambdaQueryWrapper<Courses> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(className), Courses::getClassName, className);

        List<Courses> list = this.list(wrapper);
        com.github.pagehelper.Page<Courses> p = (Page<Courses>) list;


        //执行查询
        return new PageBean(p.getTotal(), p.getResult());
    }


    @Override
    public void deleteCourse(Long id) {
        //拿到的是课程id 将该id拿去到选课单中差 看是否有数据
        LambdaQueryWrapper<CourseVariable> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CourseVariable::getCuid, id);

        //如果课程已有学生选择
        if (courseVariableMapper.selectCount(lambdaQueryWrapper) != 0) {
            //则连带删除
            courseVariableMapper.delete(lambdaQueryWrapper);
            this.removeById(id);
        } else {
            this.removeById(id);
        }
    }
}




